package com.xiaoyu.awakening.common.core.exception;

import com.xiaoyu.awakening.common.core.dto.Result;
import com.xiaoyu.awakening.common.core.exception.status.CommonReturnCode;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Type;

/**
 * 全局异常处理
 *
 * @author wangxiaoyu
 * @since v1.0
 */
@Log4j2
@ControllerAdvice
public class GlobalExceptionHandler extends RequestBodyAdviceAdapter {

    /**
     * 检验异常处理
     *
     * @param e 异常
     * @author wangxiaoyu
     * @since v1.0
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result<String> bindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getDefaultMessage()).append("!");
        }
        log.warn("业务校验异常,{}", errorMessage);
        return Result.fail(errorMessage.toString());
    }

    /**
     * 检验异常处理
     *
     * @param e 异常
     * @author wangxiaoyu
     * @since v1.0
     */
    @ExceptionHandler(value = AwkBusinessException.class)
    @ResponseBody
    public Result<String> businessException(AwkBusinessException e) {
        return Result.fail();
    }


    /**
     * 全局异常处理
     *
     * @param e 异常
     * @author wangxiaoyu
     * @since v1.0
     */
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Result<String> globalException(Throwable e) {
        log.error("系统未定义的错误:", e);
        return Result.fail(CommonReturnCode.C999999);
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return false;
    }
}
